package com.ssy.lingxi.search.controller.pc.channel;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.constant.tree.Node;
import com.ssy.lingxi.common.controller.BaseController;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.search.api.model.request.channel.ChannelCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.request.channel.ChannelShopSearchRequest;
import com.ssy.lingxi.search.api.model.response.AttributeResponse;
import com.ssy.lingxi.search.api.model.response.BrandResponse;
import com.ssy.lingxi.search.api.model.response.CategoryTreeBrandResponse;
import com.ssy.lingxi.search.api.model.response.ProvinceResponse;
import com.ssy.lingxi.search.api.model.response.channel.ChannelCommodityDetailResponse;
import com.ssy.lingxi.search.api.model.response.channel.ChannelCommoditySearchResponse;
import com.ssy.lingxi.search.service.IChannelShopService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @menu: 渠道商城
 * 渠道商城类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/8/1
 */
@RestController
@RequestMapping("/search/shop/channel")
public class ChannelShopController extends BaseController {

    @Resource
    private IChannelShopService channelService;

    @Resource
    private IRedisStringUtils redisStringUtils;


    /**
     * 查询品类树
     * @param channelMemberId 渠道会员id
     */
    @RequestMapping(value = "/getCustomerCategoryTree", method = RequestMethod.GET)
    public Wrapper<List<CategoryTreeBrandResponse>> getCustomerCategoryTree(@RequestParam(value = "channelMemberId") Long channelMemberId) {
        Long shopId = this.getHeadersShopId();
        List<Node> categoryTree = channelService.getCategoryTree(channelMemberId, shopId);
        List<CategoryTreeBrandResponse> categoryTreeBrandResponseList = categoryTree.stream().map(node -> {
            CategoryTreeBrandResponse categoryTreeBrandResponse = BeanUtil.copyProperties(node, CategoryTreeBrandResponse.class);
            Long customerCategoryId = Long.parseLong(node.getId());
            List<BrandResponse> result = channelService.getBrand(channelMemberId, shopId, customerCategoryId);
            categoryTreeBrandResponse.setBrandList(new HashSet<>(result));
            return categoryTreeBrandResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(categoryTreeBrandResponseList);
    }

    /**
     * 查询商品属性
     * @param categoryId 品类id
     * @param channelMemberId 渠道会员id
     */
    @RequestMapping(value = "/getCustomerAttributeByCategoryId", method = RequestMethod.GET)
    public Wrapper<List<AttributeResponse>> getCustomerAttributeByCategoryId(@RequestParam(value = "channelMemberId") Long channelMemberId, @RequestParam(value = "categoryId") Long categoryId) {
        Long shopId = this.getHeadersShopId();
        return Wrapper.success(channelService.getAttributeByCategoryId(shopId, channelMemberId, categoryId));
    }

    /**
     * 查询商品品牌
     * @param channelMemberId 渠道会员id
     */
    @RequestMapping(value = "/getBrand", method = RequestMethod.GET)
    public Wrapper<List<BrandResponse>> getBrand(@RequestParam(value = "channelMemberId") Long channelMemberId) {
        Long shopId = this.getHeadersShopId();
        return Wrapper.success(channelService.getBrand(channelMemberId, shopId, null));
    }

    /**
     * 查询归属地市
     * @param channelMemberId 渠道会员id
     */
    @RequestMapping(value = "/getArea", method = RequestMethod.GET)
    public Wrapper<List<ProvinceResponse>> getArea(@RequestParam(value = "channelMemberId") Long channelMemberId) {
        Long shopId = this.getHeadersShopId();
        return Wrapper.success(channelService.getArea(shopId, channelMemberId));
    }

    /**
     * 查询渠道商品最大价格(积分)
     * @return
     */
    @RequestMapping(value = "/getCommodityMaxPrice", method = RequestMethod.GET)
    public Wrapper<Double> getCommodityMaxPrice(@RequestParam(value = "channelMemberId", required = false) Long channelMemberId) {
        return Wrapper.success(channelService.getCommodityMaxPrice(channelMemberId));
    }

    /**
     * 查询商品列表
     * @param channelShopSearchRequest 查询条件实体
     */
    @RequestMapping(value = "/getCommodityList", method = RequestMethod.POST)
    public Wrapper<PageData<ChannelCommoditySearchResponse>> searchCommodityList(@RequestBody ChannelShopSearchRequest channelShopSearchRequest) {
        Long shopId = this.getHeadersShopId();
        //渠道
        Long channelMemberId = channelShopSearchRequest.getChannelMemberId();
        Long channelMemberRoleId = channelShopSearchRequest.getChannelMemberRoleId();
        if(channelMemberId == null || channelMemberId < 0 || channelMemberRoleId == null || channelMemberRoleId < 0){
            throw new BusinessException(ResponseCode.SEARCH_CHANNEL_NOT_EXIST);
        }
        //获取登录用户信息
        UserLoginCacheDTO sysUser = this.getSysUser();
        Long loginUserMemberId = sysUser.getMemberId();
        Long loginUserMemberRoleId = sysUser.getMemberRoleId();
        //参数
        ChannelCommoditySearchRequest commoditySearchRequest = this.modelMapper.map(channelShopSearchRequest, ChannelCommoditySearchRequest.class);
        commoditySearchRequest.setShopId(shopId);

        //判断是否登录自己的渠道商城
        if(channelMemberId.equals(loginUserMemberId) && channelMemberRoleId.equals(loginUserMemberRoleId)){
            //判断当前登录用户是供应商角色还是采购商角色
            Integer memberRoleType = sysUser.getMemberRoleType();
            if(RoleTypeEnum.SERVICE_PROVIDER.getCode().equals(memberRoleType)){
                Long childChannelMemberId = commoditySearchRequest.getChildChannelMemberId();
                Long childChannelMemberRoleId = commoditySearchRequest.getChildChannelMemberRoleId();
                if(childChannelMemberId == null || childChannelMemberId < 0 || childChannelMemberRoleId == null || childChannelMemberRoleId < 0){
                    throw new BusinessException(ResponseCode.SEARCH_CHILD_CHANNEL_NOT_EXIST);
                }
                commoditySearchRequest.setChildChannelMemberId(childChannelMemberId);
                commoditySearchRequest.setChildChannelMemberRoleId(childChannelMemberRoleId);
            }else{
                commoditySearchRequest.setChildChannelMemberId(loginUserMemberId);
                commoditySearchRequest.setChildChannelMemberRoleId(loginUserMemberRoleId);
            }
        }else{
            List<Long> upperChannelMemberIds = sysUser.getUpperChannelMemberIds();
            if(upperChannelMemberIds.contains(channelMemberId)){
                commoditySearchRequest.setChildChannelMemberId(loginUserMemberId);
                commoditySearchRequest.setChildChannelMemberRoleId(loginUserMemberRoleId);
            }else{
                throw new BusinessException(ResponseCode.SEARCH_JOIN_UPPER_CHANNEL_NOT_EXIST);
            }
        }

        //通过商城id查找商城类型
        Integer type = ShopTypeEnum.CHANNEL.getCode();
        String shopRedis = redisStringUtils.hGet(Constants.REDIS_KEY_SHOP, String.valueOf(shopId), Constants.REDIS_PLATFORM_MANAGE_INDEX);
        if(StringUtils.isNotEmpty(shopRedis)){
            JSONObject jsonObject = JSONUtil.parseObj(shopRedis);
            type = jsonObject.getInt("type");
        }
        return Wrapper.success(channelService.searchCommodityList(sysUser, commoditySearchRequest, true, ShopTypeEnum.CHANNEL_SCORE.getCode().equals(type)));
    }

    /**
     * 查询商品详情
     * @param channelMemberId 渠道会员id
     * @param commodityId 商品id
     */
    @RequestMapping(value = "/getCommodityDetail", method = RequestMethod.GET)
    public Wrapper<ChannelCommodityDetailResponse> getCommodityDetail(@RequestParam(value = "channelMemberId") Long channelMemberId, @RequestParam("commodityId") Long commodityId) {
        Long shopId = this.getHeadersShopId();
        //获取用户信息
        UserLoginCacheDTO sysUser = this.getSysUser();
        return Wrapper.success(channelService.getCommodityDetail(shopId, commodityId, channelMemberId, sysUser));
    }

    /**
     * 通过商品skuId查询商品详情
     * @param channelMemberId 渠道会员id
     * @param commoditySkuId 商品id
     */
    @RequestMapping(value = "/getCommodityDetailBySkuId", method = RequestMethod.GET)
    public Wrapper<ChannelCommodityDetailResponse> getCommodityDetailBySkuId(@RequestParam(value = "channelMemberId") Long channelMemberId, @RequestParam("commoditySkuId") Long commoditySkuId) {
        Long shopId = this.getHeadersShopId();
        //获取用户信息
        UserLoginCacheDTO sysUser = this.getSysUser();
        return Wrapper.success(channelService.getCommodityDetailBySkuId(shopId, commoditySkuId, channelMemberId, sysUser));
    }
}
